$(function () {

    var context = $('.questionContext').text();
    wShareFn.Focus.init({
        ele: '.questionShareBtn',
        opt: checkBaseShare(shareChannel),
        title : context.length>10?context.substring(0,10):context,
        url : window.location.href,
        lookNum : $('#browseNum').val()
    });

    var questionId = $("#questionId").val();
    var questioner = JSON.parse($("#questioner").val());
    var attender = JSON.parse($("#attender").val());
    var isFree = $("#question-isFree").val();

    if(isFree==1 || questioner || attender){
        getReplyList(1);
    }

    commFn();

    $("body").on("click","#addQuestionBtn",function () {//点击追问，弹出输入框
        addQuestion()
    }).on('click','#save-question-add',function () {//保存追问
        submitQuestionAdd();
    }).on("click","div.page-infinite__wrap",function () {//当底部评论输入框失去焦点，还原样式
        resetReplyForm();
        resetCommentInp();
    }).on("click",".question-wg-btn",function () {//1元围观
        window.location.href = baseloaction + '/mobile/uc/order/initPayOrder?orderType=COMMON&shopData='+questionId+'-ATTEND-1&shareKey=';
    }).on("click","#commentBtn",function () {//提交评论
        var context = $("#commentInp").val();
        submitQuestionReply(1, context);
    }).on("click","#commentBtn-pop",function () {//提交评论
        var context = $("#commentInp-pop").val();
        submitQuestionReply(2, context);
    }).on("click",".icon-message",function () {//去回复
        $("#commentInp").focus();
        var replyId = $(this).parent().data("id");
        var toUserId = $(this).parent().attr("touserid");
        var userName = $("#reply-user-"+replyId).html();
        setReplyForm(replyId, toUserId, 1);
        setCommentInp("commentInp", userName);
    }).on("click",".question-reply-item",function () {//去回复
        $("#commentInp").focus();
        var obj = $(this);
        var parentId = obj.parents("li").find("section.huifu").find("span").data("id");
        var toUserId = obj.data("id");
        var userName = obj.find("span[username]").html();
        userName = userName.substr(0,userName.length-1);
        setReplyForm(parentId, toUserId, 1);
        setCommentInp("commentInp", userName);
    }).on("click",".allreply-item",function () {//去回复
        $("#commentInp-pop").val("");
        $("#commentInp-pop").focus();
        var obj = $(this);
        var replyId = $("#reply-id").val();
        var _user = $(obj.parents("li").find("span")[0]);
        var toUserId = _user.data("id");
        var userName = _user.html();
        setReplyForm(replyId, toUserId, 2);
        setCommentInp("commentInp-pop", userName);
    }).on("click","#reply-context",function () {
        $("#commentInp-pop").val("");
        $("#commentInp-pop").focus();
        var replyId = $("#reply-id").val();
        var toUserId = $("#reply-userid").val();
        var userName = $("#reply-user").html();
        setReplyForm(replyId, toUserId, 2);
        setCommentInp("commentInp-pop", userName);
    }).on('click', '.allReplyBtn', function () {//查看全部评论
        var obj = $(this);
        allReplyFn(obj);
    }).on('click', '.topic-photo-popup', function () {
        var that =$(this);
        var imgs = that.parent('section').parent('div').find('img');
        openPhotoBrowser(that.next(),imgs);
    });

    /**
     * 加载问题评论列表
     * @param pageNo
     */
    function getReplyList(pageNo) {
        var params = {"questionId":questionId,"parentId":0};
        params = JSON.stringify(params);
        loadMobilePathData({
            url: baseloaction + '/mobile/qa/queryQaReplyList',
            params: params,
            contextId: 'reply-list-content',
            pageCall: getReplyList,
            pageNo: pageNo,
            callback: function (pageNo) {

            }
        })
    }

    //弹出追问输入框
    function addQuestion() {
        $.popup('.toQuestionAddPopup');
        $("#questionAdd-qaId").val($("#questionId").val());
    }

    /**
     * 保存追问
     */
   function submitQuestionAdd() {
       var params = $('#questionAdd-form').serializeJSON();
       params = JSON.stringify(params);
       $.ajax({
           url: baseloaction + '/mobile/uc/qa/add/saveQuestionAdd',
           data: params,
           type: 'post',
           dataType: 'json',
           contentType: 'application/json;charset=utf-8',
           success: function (result) {
               $.toast(result.message);
               if(result.success){
                   if(result.addCount == 2){
                       $("#addQuestionBtn").removeClass("button-danger").addClass("button-light").removeAttr("id");
                   }
                   $(".close-popup").click();
                   $("#question-addContext").val("");
                   var addCount =  result.addCount==1?'一':'二';
                   var _html = $("#questionAdd-content").html() +  " <li class=\"question-aq-txt__wrap mt5\">\n" +
                   "                                                            <div class=\"item-content\">\n" +
                   "                                                                <div class=\"item-media\">\n" +
                   "                                                                    <span class=\"fs6 c-green\">追问"+addCount+"</span>\n" +
                   "                                                                </div>\n" +
                   "                                                                <div class=\"item-inner\">\n" +
                   "                                                                    <span class=\"fs6 c-333\">"+result.entity.addContext+"</span>\n" +
                   "                                                                </div>\n" +
                   "                                                            </div>\n" +
                   "                                                        </li>";
                   $("#questionAdd-content").html(_html);
               }
           },
           error: function (error) {
               $.toast('系统繁忙，请稍后重试');
           }
       })
   }

    /**
     * 评论交互
     */
    function commFn() {
        $('#commentInp').focus(function () {    //获得焦点
            $(this).parent().siblings('.external').hide();
            $(this).next('#commentBtn').show();
            $(this).parent('.inp-txt__wrap').css('width', '100% !important')
            $(this).css({'width': '84%', 'line-height': '.96rem'});
        });
    }

    //重置评论form表单
    function resetReplyForm() {
        var _input = $("#reply-form input");
        $.each(_input, function (index, _em) {
            $(_em).val(null);
        });
    }

    //重置评论框样式
    function resetCommentInp() {
        var _commentInp = $('#commentInp');
        _commentInp.attr("placeholder","写评论");
        _commentInp.val("");
        _commentInp.parent().siblings('.external').css('display', 'block');
        _commentInp.next('#commentBtn').hide();
        $(this).parent('.inp-txt__wrap').css('width', '45% !important')
        _commentInp.css({'width': '90%', 'line-height': '1.5rem'});
    }

    /**
     * 提交评论
     * @param type 页面评论与弹框评论的区别  1:页面评论  2:弹框评论
     * @param context 评论内容
     */
    function submitQuestionReply(type, context) {
        var params;

        if(type == 1){
            $("#save-reply-qaId").val(questionId);
            $("#save-reply-context").val(context);
            params = $("#reply-form").serializeJSON();
        }
        if(type == 2){
            $("#save-reply-qaId-pop").val(questionId);
            $("#save-reply-context-pop").val(context);
            params = $("#reply-form-pop").serializeJSON();
        }

        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + "/mobile/uc/qa/reply/saveQaReply",
            data: params,
            type:"post",
            dataType:"json",
            contentType: 'application/json;charset=utf-8',
            success:function (result) {
                $.toast(result.message);
                if(result.success){
                    if(type==1){
                        resetReplyForm();
                        resetCommentInp();
                        $("#reply-list-content").html('');
                        $(".infinite-scroll-preloader").remove();
                        getReplyList(1);
                    }else if(type ==2){
                        $("#commentInp-pop").val("");
                        getChildReplyList(1);
                    }
                }
            },
            error:function () {
                $.toast("系统繁忙，请稍后重试");
            }
        })
    }

    /**
     * 设置评论form表单数据
     *
     * @param parentId 父级评论ID
     * @param toUserId 被回复者ID
     * @Param type 区分页面form表单与弹框form表单  1页面， 2弹框
     */
    function setReplyForm(parentId, toUserId, type) {
        if(type == 1){
            $("#save-reply-parentId").val(parentId);
            $("#save-reply-toUserId").val(toUserId);
        }else {
            $("#save-reply-parentId-pop").val(parentId);
            $("#save-reply-toUserId-pop").val(toUserId);
        }
    }

    //设置输入框placeholder属性
    function setCommentInp(inputId, userName) {
        $("#"+inputId).attr("placeholder", "@"+ userName +"：");
    }

    /**
     * 查看全部评论
     */
    function allReplyFn(obj) {
        $.popup('.allReplyPopup');

        var replyId = obj.data("id");
        var toUserId = $("#reply-userid-"+replyId).attr("touserid");
        var userName = $("#reply-user-"+replyId).html();

        $("#reply-userid").val(toUserId);
        $("#reply-id").val(replyId);

        $("#reply-user").html(userName);
        $("#reply-img").attr("src",document.getElementById("reply-img-"+replyId).src);
        $("#reply-date").html($("#reply-date-"+replyId).html());
        $("#reply-context").html($("#reply-context-"+replyId).html());

        setReplyForm(replyId, toUserId, 2);
        setCommentInp("commentInp-pop",userName);
        getChildReplyList(1);
    }

    //查看全部回复
    function getChildReplyList(pageNo) {
        var params = {"parentId":$("#reply-id").val()};
        params = JSON.stringify(params);
        loadMobilePathData({
            url: baseloaction + '/mobile/qa/queryChildQaReplyList',//请求url
            contextId:'allreply-list-content',//请求成功后数据内容添加的地方
            pageNo:pageNo,//页面码，可以不传
            pageCall:getChildReplyList,//分页方法（一般调用自身）
            params:params,//查询参数
            callback:function (pageNo) {

            }
        });
    }
});